<?php
/**
 * 律所管理控制器
 */

declare (strict_types = 1);

namespace app\controller\lawyer;

use app\BaseController;
use app\model\lawyer\Lawfirm as LawfirmModel;
use think\facade\Db;
use think\facade\Request;

class Lawfirm extends BaseController
{
    /**
     * 查看律所列表
     */
    public function list()
    {
        $param = Request::param();
        $page = isset($param['page']) ? (int)$param['page'] : 1;
        $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
        
        // 构建查询条件
        $params = [];
        
        // 关键词搜索
        if (!empty($param['keywords'])) {
            $params['title'] = trim($param['keywords']);
        }
        
        // 按状态筛选
        if (isset($param['status']) && $param['status'] !== '') {
            $params['status'] = $param['status'];
        }
        
        try {
            // 使用模型方法获取律所列表
            $lawfirmModel = new LawfirmModel();
            $result = $lawfirmModel->getList($params, $page, $limit);
            
            // 处理列表数据，获取省市区名称并格式化时间
            $list = $result['list']->each(function($item) {
                // 获取省市区名称
                if (!empty($item['provinceid'])) {
                    $item['province'] = Db::name('region')->where('id', $item['provinceid'])->value('name');
                }
                if (!empty($item['cityid'])) {
                    $item['city'] = Db::name('region')->where('id', $item['cityid'])->value('name');
                }
                if (!empty($item['distid'])) {
                    $item['dist'] = Db::name('region')->where('id', $item['distid'])->value('name');
                }
                
                return $item;
            });
            
            return $this->success([
                'list' => $list,
                'total' => $result['total'],
                'page' => $page,
                'limit' => $limit
            ], 'success');
        } catch (\Exception $e) {
            return $this->error('获取失败', 500);
        }
    }
    
    /**
     * 查看单个律所信息
     */
    public function view()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return $this->error('参数错误', 400);
        }
        
        try {
            // 使用模型方法获取律所信息
            $lawfirmModel = new LawfirmModel();
            $lawfirm = $lawfirmModel->getInfoById($param['id']);
            
            if (empty($lawfirm)) {
                return $this->error('律所信息不存在', 404);
            }
            
            // 转换为数组以便处理
            $lawfirm = $lawfirm->toArray();
            
            // 获取省市区名称
            if (!empty($lawfirm['provinceid'])) {
                $lawfirm['province'] = Db::name('region')->where('id', $lawfirm['provinceid'])->value('name');
            }
            if (!empty($lawfirm['cityid'])) {
                $lawfirm['city'] = Db::name('region')->where('id', $lawfirm['cityid'])->value('name');
            }
            if (!empty($lawfirm['distid'])) {
                $lawfirm['dist'] = Db::name('region')->where('id', $lawfirm['distid'])->value('name');
            }
            
            // 格式化时间 - 修复date()函数参数类型错误
            $lawfirm['create_time'] = $lawfirm['create_time'] ? date('Y-m-d H:i', intval($lawfirm['create_time'])) : '';
            $lawfirm['update_time'] = $lawfirm['update_time'] ? date('Y-m-d H:i', intval($lawfirm['update_time'])) : '';
            
            return $this->success($lawfirm, '获取成功');
        } catch (\Exception $e) {
            return $this->error('获取失败', 500);
        }
    }
    
    /**
     * 获取启用的律所列表（用于下拉选择）
     */
    public function set()
    {
        try {
            // 使用模型方法获取启用的律所列表
            $lawfirmModel = new LawfirmModel();
            $list = $lawfirmModel->getActiveLawfirms();
            
            return $this->success($list, '获取成功');
        } catch (\Exception $e) {
            return $this->error('获取失败', 500);
        }
    }
    
    /**
     * 新增律所
     */
    public function add()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['title'])) {
            return $this->error('律所名称不能为空', 400);
        }
        
        $data = [
            'title' => $param['title'],
            'provinceid' => $param['provinceid'] ?? 0,
            'cityid' => $param['cityid'] ?? 0,
            'distid' => $param['distid'] ?? 0,
            'address' => $param['address'] ?? '',
            'info' => $param['info'] ?? '',
            'status' => $param['status'] ?? 1
        ];
        
        try {
            // 使用模型方法创建律所
            $lawfirmModel = new LawfirmModel();
            $lawfirmId = $lawfirmModel->createLawfirm($data);
            
            return $this->success(['id' => $lawfirmId], '添加成功');
        } catch (\Exception $e) {
            return $this->error('添加失败', 500);
        }
    }
    
    /**
     * 编辑律所
     */
    public function edit()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['id'])) {
            return $this->error('参数错误', 400);
        }
        
        if (empty($param['title'])) {
            return $this->error('律所名称不能为空', 400);
        }
        
        $data = [
            'title' => $param['title'],
            'provinceid' => $param['provinceid'] ?? 0,
            'cityid' => $param['cityid'] ?? 0,
            'distid' => $param['distid'] ?? 0,
            'address' => $param['address'] ?? '',
            'info' => $param['info'] ?? '',
            'status' => $param['status'] ?? 1
        ];
        
        try {
            // 使用模型方法更新律所
            $lawfirmModel = new LawfirmModel();
            $result = $lawfirmModel->updateLawfirm($param['id'], $data);
            
            if ($result) {
                return $this->success('保存成功');
            } else {
                return $this->error('保存失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('保存失败', 500);
        }
    }
    
    /**
     * 删除律所（软删除）
     */
    public function del()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            // 检查是否有律师关联此律所
            $lawyerCount = Db::name('lawyer')
                ->where('firmid', $param['id'])
                ->where('status', '>', -1) // 使用status>-1代替delete_time=0
                ->count();
            
            if ($lawyerCount > 0) {
                return json(['code' => 400, 'msg' => '该律所有关联的律师，不能删除']);
            }
            
            // 使用模型方法删除律所
            $lawfirmModel = new LawfirmModel();
            $result = $lawfirmModel->deleteLawfirm($param['id']);
            
            if ($result) {
                return json(['code' => 0, 'msg' => '删除成功']);
            } else {
                return json(['code' => 500, 'msg' => '删除失败']);
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '删除失败: ' . $e->getMessage()]);
        }
    }
}